import CryptoJS from 'crypto-js';
import dayjs from 'dayjs';
/**
 * 防抖方法封装
 *
 * @param fn 目标方法
 * @param ms 防抖延迟
 * @returns
 */
export const debounce = (fn: (...params: any[]) => any, ms = 200) => {
  let timer = 0;
  return (...params: any[]) => {
    if (timer) {
      clearTimeout(timer);
    }

    timer = window.setTimeout(() => {
      fn.apply(this, params);
      timer = 0;
    }, ms);
  };
};

/**
 * 获取距离body的位置
 *
 * @param targetEle
 * @returns
 */
export const getOffset = (targetEle: HTMLElement) => {
  let parentEle = targetEle.offsetParent as HTMLElement;
  let offsetTop = targetEle.offsetTop;
  let offsetLeft = targetEle.offsetLeft;

  if (parentEle?.nodeName.toLowerCase() !== 'body') {
    while (parentEle) {
      offsetTop += parentEle?.offsetTop;
      offsetLeft += parentEle?.offsetLeft;
      parentEle = parentEle?.offsetParent as HTMLElement;
    }
  }

  return {
    left: offsetLeft,
    top: offsetTop,
  };
};

export const classnames = (classList: (string | false)[]) => {
  return classList.filter((item) => item !== false).join(' ');
};
// 处理post请求数组参数问题
export const paramsSerializer = (params: any): string => {
  const result: string[] = [];
  for (const field in params) {
    if (params[field] === undefined || params[field] === null) {
      result.push(`${field}=`);
      continue;
    }
    if (Array.isArray(params[field])) {
      result.push(params[field].map((_: any) => `${field}=${_}`).join('&'));
    } else {
      result.push(`${field}=${encodeURIComponent(params[field])}`);
    }
  }
  return result.join('&');
};
// 获取窗口滚动条高度
export const getScrollTop = (): number => {
  let scrollTop = 0;
  if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop;
  } else if (document.body) {
    scrollTop = document.body.scrollTop;
  }
  return scrollTop;
};
// 获取页面总高度
export const getScrollHeight = (): number => {
  let scrollHeight = 0;
  if (document.documentElement && document.documentElement.scrollHeight) {
    scrollHeight = document.documentElement.scrollHeight;
  } else if (document.body) {
    scrollHeight = document.body.scrollHeight;
  }
  return scrollHeight;
};
// 取窗口可视范围的高度
export const getClientHeight = (): number => {
  let clientHeight = 0;
  if (document.body.clientHeight && document.documentElement.clientHeight) {
    clientHeight =
      document.body.clientHeight < document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight;
  } else {
    clientHeight =
      document.body.clientHeight > document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight;
  }
  return clientHeight;
};
/**
 * 关键字变色
 * @params content 内容
 * @params keyword 关键词
 * @params tagName 标签名 默认span
 */
export const warpTag = (content: string, keyword: string, tagName: string = 'span') => {
  if (content === 'No results') {
    return content;
  }
  const a = content.toLowerCase();
  const b = keyword.toLowerCase();
  const indexof = a.indexOf(b);
  const c = indexof > -1 ? content.substr(indexof, keyword.length) : '';
  const val = `<${tagName} style="color:red;font-weight: 700;">${c}</${tagName}>`;
  const regS = new RegExp(keyword, 'gi');
  return content.replace(regS, val);
};

/**
 * 以指定符号分隔数组项
 * @param {*} arr
 * @param {*} value 指定的数组项 默认是当前
 * @param {*} separator
 */
export const join = (arr: any[] = [], value: string | number, separator = ',') => {
  const newArr = arr.map((item) => item[value]);
  return newArr.join(separator);
};
/**
 *
 * @param name
 * @returns
 */
export function getQueryString(name: string) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  let r = window.location.search.substring(1).match(reg); //获取url中"?"符后的字符串并正则匹配
  let context = '';
  if (r != null) context = decodeURIComponent(r[2]);
  r = null;
  return context == null || context == '' || context == 'undefined' ? '' : context;
}
/**
 * 对比当前token时间是否已经过期
 */
export function checkTokenTime() {
  const tokenString = localStorage.getItem(BASE_TOKEN_NAME);
  if (!tokenString) return false;
  const tokenObj = JSON.parse(tokenString);
  return tokenObj.tokenSurvivalTime < Date.now();
}
/**
 * 本系统时间展示处理方法  一天以内显示 多少多少(秒 小时)前 大于一天显示正常时间
 * @param time1 目标时间
 * @param time2 一般是当前时间
 */
export const showTimeText = (time1: any, time2: any = new Date()) => {
  const newTime1 = dayjs(time1);
  const newTime2 = dayjs(time2);
  const diff = newTime2.diff(newTime1, 'day');
  console.log(diff);

  if (diff !== 0) {
    return newTime1.format('YYYY-MM-DD HH:mm:ss');
  } else {
    return newTime1.fromNow();
  }
};

/**
 * 判断日期是否连续，不连续则拆分
 * @param arr_days 日期数组
 * @returns 拆分后的二维数组
 */
export const continueDays = (arr_days: string[]) => {
  // 先排序，然后转时间戳
  const days = arr_days.sort().map((d, i) => {
    const dt = new Date(d);
    dt.setDate(dt.getDate() + 4 - i); // 处理为相同日期
    // 抹去 时 分 秒 毫秒，如果日期带时间可以把这段代码加上
    // dt.setHours(0)
    // dt.setMinutes(0)
    // dt.setSeconds(0)
    // dt.setMilliseconds(0)
    return +dt;
  });
  // 相同日期进行去重
  const newDays = [...new Set(days)];
  const dataArr: string[][] = [];
  newDays.forEach((element) => {
    const arr: string[] = [];
    days.forEach((item, i) => {
      if (item == element) {
        arr.push(arr_days[i]);
      }
    });
    dataArr.push(arr);
  });
  // 这里返回的是二维数组
  return dataArr;
};

/**
 *
 * @param val 加密字符
 * @returns 加密后的值
 */
export const aesEncryption = (val: string | number) => {
  const key: string = 'wjhandlbb_key000';
  const iv: string = 'wjhandlbb_vi0000';
  const _word = CryptoJS.enc.Utf8.parse(val),
    _key = CryptoJS.enc.Utf8.parse(key),
    _iv = CryptoJS.enc.Utf8.parse(iv);
  const encrypted = CryptoJS.AES.encrypt(_word, _key, {
    iv: _iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};

// 未登录如何返回值
export const notLoginResHandler = (request: any): COMMON.BaseSuccess | any => {
  const tokenString = localStorage.getItem(BASE_TOKEN_NAME);
  if (!tokenString) {
    return new Promise<COMMON.BaseSuccess>((res) => {
      res({
        code: 200,
        data: undefined,
        message: '',
      });
    });
  }
  return request();
};

// 未登录且用户手动触发需要登录的接口时的处理办法
export const showLoginModal = (request: any): COMMON.BaseSuccess | any => {
  const tokenString = localStorage.getItem(BASE_TOKEN_NAME);
  if (!tokenString) {
    return new Promise<COMMON.BaseSuccess>((res, reject) => {
      window.showLoginModal(true);
      reject('未登录的请求');
    });
  } else {
    return request;
  }
};
// 是否是不需要登录的页面
export const isPass = (location?: any) => {
  return WHITE_LIST.some((item: string) => {
    return (
      (location || window.location).pathname.startsWith(item) ||
      (location || window.location).pathname === '/'
    );
  });
};
